import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import { PurchaseService } from './purchase.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { UseLog } from 'src/log/useLog.decorator';
import { Purchase } from './Purchase.entity';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { DeptService } from 'src/dept/dept.service';
import { In } from 'typeorm';
import { NotFound } from 'src/util/http';

@Controller('api/purchase')
@ApiTags("采购管理")
@UseGuards(AuthGuard("jwt"))
export class PurchaseController {
    constructor(
        private readonly purchaseService: PurchaseService,
        private readonly deptService: DeptService
    ) { }

    @Get("get")
    @ApiOperation({ summary: "获取采购" })
    get(
        @CurrentUser() user: UserSys
    ) {
        return this.purchaseService.purchase.find({
            where: {
                system: {
                    id: user.system.id
                }
            },
            relations: ["depts", "system"],
            order: {
                id: "desc"
            }
        })
    }

    @Post("add")
    @UseLog("添加采购")
    async add(
        @Body() { depts, ...body }: Purchase,
        @CurrentUser() user: UserSys
    ) {
        const data = await this.deptService.dept.find({
            where: {
                id: In(depts)
            }
        })
        return await this.purchaseService.purchase.save(
            this.purchaseService.purchase.create({
                depts: data,
                system: user.system,
                ...body
            })
        )
    }

    @Post(":id/upd")
    @UseLog("修改采购")
    async upd(
        @Body() { depts, ...body }: Purchase,
        @CurrentUser() user: UserSys,
        @Param("id") id: number
    ) {

        const entity = await this.purchaseService.purchase.findOne({ where: { id } });
        if (!entity) throw NotFound
        const data = await this.deptService.dept.find({
            where: {
                id: In(depts)
            }
        })
        return await this.purchaseService.purchase.save({
            ...entity,
            ...body,
            depts: data
        })
    }

    @Post("del")
    @UseLog("删除采购")
    del(
        @Body() { ids }
    ) {
        return this.purchaseService.purchase.delete({
            id: In(ids)
        })
    }

}
